package top.yxqz.session.demo.test;

import top.yxqz.session.demo.school.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Mr.余
 * @date 2022/11/28
 * @package top.yxqz.session.demo.test
 * 页面
 * 处理登录
 */
@WebServlet("/stulogin")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf8"); //解决中文乱码
        PrintWriter writer = response.getWriter();//创建writer对象
        String uri = request.getRequestURI();


//       构架动态网页：仿造jsp的实现
        writer.println("<form action=" + uri + ">\n" +
                "    用户名：<input type=\"text\" name=\"userName\"> <br>\n" +
                "    密 码：<input type=\"password\" name=\"password\"> <br>\n" +
                "    <input type=\"submit\" value=\"提交\">\n" +
                "</form>");

        String userName = request.getParameter("userName");
        String password = request.getParameter("password");

        Student student = new Student(userName, password);//用对象来封装前端的数据


//        制造数据（获取数据库的数据）
        String usernameData = "yxqz";
        String passwordData = "123456";

//        做登录逻辑判断
        if (usernameData.equals(student.getUserName()) &&
                passwordData.equals(student.getPassword())) {
//            登录成功
            HttpSession session = request.getSession(true); //得到session会话对象
            session.setAttribute("stu",student);//将登录成功的学生对象，放入到session会话域
            String id = session.getId();//得到sessionid
//            创建一个Cookie对象(cookie的名字，cookie的内容，就是一个字符串）
            Cookie cookie  = new Cookie("JSESSIONID",id);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*7); //单位是秒
            response.addCookie(cookie); //将cookie放在浏览器中

//            重定向到登录成功的页面
            response.sendRedirect(getServletContext().getContextPath()+"/index");

        } else {
//登录失败

        }

    }
}
